package com.example.textview.util;

import android.os.Looper;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class Tcpclass {


    //    Socket
    private Socket socket;
    //    IP地址
    private String ipAddress;
    //    端口号
    private int port;
    private Thread thread;
    //    Socket输出流
    private OutputStream outputStream;
    //    Socket输入流
    private InputStream inputStream;

    //    连接回调
    public OnServerConnectedCallbackBlock connectedCallback;
    //    断开连接回调(连接失败)
   public OnServerDisconnectedCallbackBlock disconnectedCallback;

    //    接收信息回调
    private OnReceiveCallbackBlock receivedCallback;

    public void connect(final String ipAddress, final int port) {

        thread = new Thread(new Runnable() {


            @Override
            public void run() {
                try {
                     Looper.prepare();//增加部分

//                    socket = new Socket(ipAddress, port);
//                    socket.setSoTimeout ( 2 * 1000 );//设置超时时间

                    Log.d("hex","开始连接！");
                    socket = new Socket();
                    SocketAddress socAddress = new InetSocketAddress(ipAddress, port);
                    socket.connect(socAddress, 5000);


                    if (isConnected()) {
//                        ipAddress = ipAddress;
//                        this.port = port;
                        Log.d("hex","连接成功！");

                        if (connectedCallback != null) {
                            connectedCallback.callback();
                        }
                        outputStream = socket.getOutputStream();
                        inputStream = socket.getInputStream();
                        // receive();

                    } else {

                        if (disconnectedCallback != null) {
                            disconnectedCallback.callback(new IOException("连接失败"));
                        }
                    }

                    Looper.loop();//增加部分


                } catch (IOException e) {
                    e.printStackTrace();

                    if (disconnectedCallback != null) {
                        disconnectedCallback.callback(e);
                    }
                }
            }
        });

        thread.start();


    }



    private void waitForMills(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送数据
     *
     * @param data 数据
     */
    public void send(final byte[] data) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (socket != null) {
                    try {
                        outputStream.write(data);
                        outputStream.flush();
                       String str1= receivedada("1");

                       if(str1!=null)
                       Log.d("hex",str1);


                    } catch (IOException e) {
                        e.printStackTrace();

                    }
                } else {
                    connect();
                }
            }
        }).start();

    }


    public void send(final byte[] data,final String adr)
    {
        if (socket != null) {
            try {
                outputStream.write(data);
                outputStream.flush();
                waitForMills(100);
                String str1= receivedada(adr);

                if(str1!=null) {

                    Log.d("hex", str1);

                    if (receivedCallback != null) {
                        receivedCallback.callback(str1,adr);


                    }
                }

            } catch (IOException e) {
                e.printStackTrace();

            }
        }

    }


    public boolean isConnected() {

        return socket.isConnected();
    }


    public interface OnServerConnectedCallbackBlock {
        void callback();
    }

    public interface OnServerDisconnectedCallbackBlock {
        void callback(IOException e);
    }


    public interface OnReceiveCallbackBlock {
        void callback(String receicedMessage,String adr);
    }
    /**
     * 连接
     */
    void connect() {
        connect(ipAddress, port);
    }


    public void receive() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    /**得到的是16进制数，需要进行解析*/
                    byte[] bt = new byte[1024];
//                获取接收到的字节和字节数
                    int length = inputStream.read(bt);
                    if (length > 0) {
//                获取正确的字节
                        byte[] bs = new byte[length];
                        System.arraycopy(bt, 0, bs, 0, length);


                        String str = bytesToHexString(bs);

                        if (str != null) {
                            if (receivedCallback != null) {
                                receivedCallback.callback(str,"123");


                            }
                        }


                    }


                }
                catch(IOException e){
                    //Log.i(TAG,"接收失败");

                }
            }
        }).start();






    }



    public String receivedada(final String adr)
    {
        try {
            /**得到的是16进制数，需要进行解析*/
            byte[] bt = new byte[1024];
//                获取接收到的字节和字节数
            int length = inputStream.read(bt);
            if (length > 0) {
//                获取正确的字节
                byte[] bs = new byte[length];
                System.arraycopy(bt, 0, bs, 0, length);


                String str = bytesToHexString(bs);

                return str;
            }

            return  null;
        }
        catch(IOException e){
            //Log.i(TAG,"接收失败");
            return  null;
        }
    }




    private String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
